package net.javalib.flickr.search.flickr;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import net.javalib.flickr.search.util.IOUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Utility class for interfacing with Flickr
 */
public class Flickr {
	
	/**
	 * Returns the Flickr search url for the given parameters
	 * @param apiKey The application api key
	 * @param term The search term
	 * @param maxResults The maximum number of results to return
	 * @return The url
	 */
	public static String getSearchURL(String apiKey, String term, int maxResults) {
		StringBuffer url = new StringBuffer("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=");
		url.append(apiKey);
		url.append("&format=json&per_page=");
		url.append(maxResults);
		url.append("&sort=relevance");
		url.append("&content_type=1&media=photos");
		url.append("&text=");
		url.append(URLEncoder.encode(term));
		return url.toString();
	}
	
	/**
	 * Parses an input stream for flickr json search result
	 */
	public static List<FlickrImage> parserJSONSearchResult(InputStream in) throws IOException {
		String jstr = IOUtil.toString(in);
		try {
			
			jstr = jstr.substring("jsonFlickrApi(".length(),jstr.length()-1);
			
			List<FlickrImage> retVal = new ArrayList<FlickrImage>(20);
			JSONObject jobj = new JSONObject(jstr);
			JSONArray photos = jobj.getJSONObject("photos").getJSONArray("photo");
			for (int x=0;x<photos.length();x++) {
				JSONObject photo = photos.getJSONObject(x);
				FlickrImage image = new FlickrImage();
				image.id = photo.getLong("id");
				image.title = photo.getString("title");
				image.farm = photo.getInt("farm");
				image.server = photo.getInt("server");
				image.secret = photo.getString("secret");
				retVal.add(image);
			}
			return retVal;
		} catch (JSONException e) {
			throw new IOException("JSON ERROR: "+e.getMessage());
		}
	}

	public static String imageUrl(FlickrImage image) {
		StringBuffer url = new StringBuffer(baseImageURL(image));
		url.append(".jpg");
		return url.toString();
	}
	
	public static String thumbnailURL(FlickrImage image) {
		StringBuffer url = new StringBuffer(baseImageURL(image));
		url.append("_s.jpg");
		return url.toString();
	}
	
	private static String baseImageURL(FlickrImage image) {
		StringBuffer url = new StringBuffer("http://farm");
		url.append(image.farm);
		url.append(".static.flickr.com/");
		url.append(image.server);
		url.append("/");
		url.append(image.id);
		url.append("_");
		url.append(image.secret);
		return url.toString();
	}
	
}

	